home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c-part2 / 13517 < prev    next >
Encoding:
Internet Message Format  |  1996-08-05  |  1.6 KB

  1. Path: mail2news.demon.co.uk!genesis.demon.co.uk
  2. From: Lawrence Kirby <fred@genesis.demon.co.uk>
  3. Newsgroups: comp.lang.c
  4. Subject: Re: convert 4 8-bit bytes in a foat
  5. Date: Mon, 08 Apr 96 12:21:00 GMT
  6. Organization: none
  7. Message-ID: <828966060snz@genesis.demon.co.uk>
  8. References: <4k5pr7$bp7@nuscc.nus.sg>
  9. Reply-To: fred@genesis.demon.co.uk
  10. X-NNTP-Posting-Host: genesis.demon.co.uk
  11. X-Newsreader: Demon Internet Simple News v1.27
  12. X-Mail2News-Path: genesis.demon.co.uk
  13.  
  14. In article <4k5pr7$bp7@nuscc.nus.sg>
  15.            eng30183@leonis.nus.sg "LEONG TUCK WAI" writes:
  16.  
  17. >Hi,
  18. >
  19. >I have 4 8-bit bytes. If I line them up in order, they actually represent 
  20. >the 32-bit float data type version of a decimal point number. So, how do 
  21. >I get the compiler to understand that, and print out the float number 
  22. >instead of giving me 4 integers?
  23.  
  24.     float f;
  25.     unsigned char a[sizeof f];
  26.  
  27.     /* Write your bytes to a by whatever means */
  28.  
  29.     memcpy(&f, a, sizeof f);
  30.  
  31.     printf("%f\n", f);
  32.  
  33. Another possibility is:
  34.  
  35.     float f;
  36.     unsigned char *ptr = (unsigned char *)&f;
  37.  
  38. You can then use ptr to write the bytes into f directly. Using unions, or
  39. char instead of unsigned char will typically work but is more likely to
  40. trip up on the letter of the standard. If you are reading from a binary
  41. file you could write:
  42.  
  43.     fread(&f, sizeof f, 1, fp)
  44.  
  45. That does assume that byte order and so on in the file are correct since
  46. you don't get a chance to alter them prior to loading into f.
  47.  
  48. -- 
  49. -----------------------------------------
  50. Lawrence Kirby | fred@genesis.demon.co.uk
  51. Wilts, England | 70734.126@compuserve.com
  52. -----------------------------------------
  53.